#
# 命名规则上，采用 项目名+云模块名+时间戳 的形式。保证命名唯一的同时，也便于通过控制台一眼能认出开通的哪个云产品是属于哪个项目的，不至于一个账号上运行多个不同的项目而混乱
# 项目地址： https://gitee.com/HuaweiCloudDeveloper/huaweicloud-solution-build-wangmarketcms
#
terraform {
        required_providers {
                huaweicloud = {
                        source  = "huawei.com/provider/huaweicloud"
                        version = "1.38.2"
                }
        }
}


# 填写华为云AK，获取步骤参考 http://help.wscso.com/35423.html 。这里填写的AK在加入系统配置时会以DSA加密后存入系统的数据库配置中。
variable "access_key_id" {
	description = "华为云的凭证 - access_key_id，系统要使用这个才能将图片等附件上传到云存储跟华为云本身进行打通。获取步骤参考 http://help.wscso.com/35423.html"
	type        = string
	validation {
		# 校验为空的情况
		condition     = var.access_key_id != ""
		error_message = "请输入 access_key_id"
	}
}
variable "secret_access_key" {
	description = "华为云的凭证 - secret_access_key，系统要使用这个才能将图片等附件上传到云存储跟华为云本身进行打通。获取步骤参考 http://help.wscso.com/35423.html"
	type        = string
	validation {
		# 校验为空的情况
		condition     = var.secret_access_key != ""
		error_message = "请输入 secret_access_key"
	}
}

# 生成随机16位的随机字符-用于密码
resource "random_string" "password" {
	length           = 16
	special          = true
	override_special = "@"
}

# 定义一些变量，时间戳的作用是避免命名重复。 使用时调用如： ${local.timestamp}
locals {
	timestamp = formatdate("YYYYMMDDhhmmss", timestamp())
	# ecs 服务器的密码
	ecspassword="${random_string.password.result}@wm"
	# obs的名称
	obsname = "kefu-${local.timestamp}"
    # obs桶策略
    obspolicy = jsonencode({"Statement":[{"Sid": "公共读-${local.obsname}","Effect": "Allow","Principal": {"ID": ["*"]},"Action": ["ListBucket","HeadBucket","GetBucketLocation","ListBucketVersions","GetObject","RestoreObject","GetObjectVersion"],"Resource": ["${local.obsname}","${local.obsname}/*"]}]})
	# AK凭证
    access_key_id     = var.access_key_id
    secret_access_key = var.secret_access_key
}

# VPC虚拟私有云。对应控制台 https://console.huaweicloud.com/vpc/
resource "huaweicloud_vpc" "vpc" {
  name = "wangmarket_vpc_${local.timestamp}"
  cidr = "192.168.0.0/16"
}
# 子网
resource "huaweicloud_vpc_subnet" "subnet" {
  name       = "wangmarket_subnet_${local.timestamp}"
  cidr       = "192.168.0.0/16"
  gateway_ip = "192.168.0.1"
  vpc_id     = huaweicloud_vpc.vpc.id
}
# 创建安全组
resource "huaweicloud_networking_secgroup" "secgroup"{
	name = "wangmarket_secgroup_${local.timestamp}"
}
# 安全组规则-开放80端口
resource "huaweicloud_networking_secgroup_rule" "secgroup_rule_80"{
	direction         = "ingress"
	ethertype         = "IPv4"
	protocol          = "tcp"
	ports	          = 80
	remote_ip_prefix  = "0.0.0.0/0"
	security_group_id = huaweicloud_networking_secgroup.secgroup.id
}
# 安全组规则-开放8081端口，用于websocket通道
resource "huaweicloud_networking_secgroup_rule" "secgroup_rule_8081"{
	direction         = "ingress"
	ethertype         = "IPv4"
	protocol          = "tcp"
	ports	          = 8081
	remote_ip_prefix  = "0.0.0.0/0"
	security_group_id = huaweicloud_networking_secgroup.secgroup.id
}
# 安全组规则-开放22端口
resource "huaweicloud_networking_secgroup_rule" "secgroup_rule_22"{
        direction         = "ingress"
        ethertype         = "IPv4"
        protocol          = "tcp"
        ports             = 22
        remote_ip_prefix  = "0.0.0.0/0"
        security_group_id = huaweicloud_networking_secgroup.secgroup.id
}
# 安全组规则-开放443端口
resource "huaweicloud_networking_secgroup_rule" "secgroup_rule_443"{
        direction         = "ingress"
        ethertype         = "IPv4"
        protocol          = "tcp"
        ports             = 443
        remote_ip_prefix  = "0.0.0.0/0"
        security_group_id = huaweicloud_networking_secgroup.secgroup.id
}
# 安全组规则-开放3306端口
resource "huaweicloud_networking_secgroup_rule" "secgroup_rule_3306"{
        direction         = "ingress"
        ethertype         = "IPv4"
        protocol          = "tcp"
        ports             = 3306
        remote_ip_prefix  = "0.0.0.0/0"
        security_group_id = huaweicloud_networking_secgroup.secgroup.id
}
# 安全组规则-允许ping程序测试弹性云服务器的连通性
resource "huaweicloud_networking_secgroup_rule" "secgroup_rule_ping"{
        direction         = "ingress"
        ethertype         = "IPv4"
        protocol          = "icmp"
		remote_ip_prefix  = "0.0.0.0/0"
        security_group_id = huaweicloud_networking_secgroup.secgroup.id
}

# 创建obs桶
resource "huaweicloud_obs_bucket" "obs" {
	bucket = "${local.obsname}"
	acl    = "public-read"
	tags   = {
		type = "bucket"
		env  = "${local.obsname}"
	}
    policy = local.obspolicy
}

# 创建弹性公网EIP
# 按流量计费方式，10MB带宽
resource "huaweicloud_vpc_eip" "eip" {
  name = "wangmarket_eip_${local.timestamp}"
  publicip {
    type = "5_bgp"
  }
  bandwidth {
    share_type  = "PER"
    name        = "wangmarket_bandwidth_${local.timestamp}"
    size        = 10
    charge_mode = "traffic"
  }
}

# 搜索CentOS7.4的镜像
data "huaweicloud_images_image" "image" {
  most_recent = true
  visibility  = "public"
  name        = "CentOS 7.4 64bit"
}
# 搜索服务器规格,1核2G内存的
data "huaweicloud_availability_zones" "myaz" {}
data "huaweicloud_compute_flavors" "myflavor" {
  availability_zone = data.huaweicloud_availability_zones.myaz.names[0]
  performance_type  = "normal"
  cpu_core_count    = 1
  memory_size       = 2
}
# 创建服务器
# 注意有坑：设置了user_data字段后，admin_pass字段将无效
resource "huaweicloud_compute_instance" "instance" {
  name              = "wangmarket_${local.timestamp}"
 #admin_pass        = "wngMarket#23"
  image_id          = data.huaweicloud_images_image.image.id
  flavor_id         = data.huaweicloud_compute_flavors.myflavor.ids[0]
  availability_zone = data.huaweicloud_availability_zones.myaz.names[0]
  security_group_ids= [huaweicloud_networking_secgroup.secgroup.id]

  network {
    uuid = huaweicloud_vpc_subnet.subnet.id
  }
  user_data           = "#!/bin/sh\ncd ~\necho ${local.ecspassword} | passwd root --stdin > /dev/null 2>&1\ntouch /root/install.properties\necho 'ecs.ip=${huaweicloud_vpc_eip.eip.address}'>>/root/install.properties\necho 'ecs.username=root'>>/root/install.properties\necho 'ecs.password=${local.ecspassword}'>>/root/install.properties\necho 'obs.bucket=${local.obsname}'>>/root/install.properties\necho 'cdndomain=${huaweicloud_obs_bucket.obs.bucket_domain_name}'>>/root/install.properties\necho 'accesskey.id=${local.access_key_id}'>>/root/install.properties\necho 'accesskey.secret=${local.secret_access_key}'>>/root/install.properties\necho 'region=${huaweicloud_obs_bucket.obs.region}'>>/root/install.properties\nwget https://gitee.com/HuaweiCloudDeveloper/huaweicloud-solution-build-kefu-im/raw/master/PrimaryLevel/user_data_install.sh -O install.sh\nchmod -R 777 install.sh\nchmod -x install.sh\nsh install.sh > install.log 2>&1"
}

# 将服务器跟弹性公网绑定
resource "huaweicloud_compute_eip_associate" "associated" {
  public_ip   = huaweicloud_vpc_eip.eip.address
  instance_id = huaweicloud_compute_instance.instance.id
}

# 输出ecs服务器的信息
output "服务器信息"{
	value = "服务器IP:${huaweicloud_vpc_eip.eip.address} 远程登录账号:root 远程登录密码:${local.ecspassword}  另外服务器自动安装的mysql了等账号密码，都存在于服务器的此文件中： /root/account.txt"
}
output "安装提示"{
	value = "服务器中的云客服系统及依赖环境正在安装部署中，请稍后，您可以等待10分钟后再尝试在浏览器中访问您的服务器IP: ${huaweicloud_vpc_eip.eip.address}  如果能打开，说明安装已经完成，可以正常使用了；如果打不开说明正在安装中，请等待几分钟再试"
}
